﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Data;

namespace Server
{
    class GameServer
    {
        private static GameServer _instance;
        public static GameServer Instance
        {
            get
            {
                if(_instance==null)
                {
                    _instance = new GameServer();
                }
                return _instance;
            }
        }

        string ip = "127.0.0.1";
        int port = 8500;
        TcpListener listener;

        HandlerCenter center = new HandlerCenter();

        //Dictionary<string, SocketClient> clients = new Dictionary<string, SocketClient>();

        public void StartUp()
        {
            LogManager.Init();

            IPAddress address = IPAddress.Parse(ip);
            listener = new TcpListener(address, port);
            listener.Start();
            LogManager.Log("服务器开始侦听");

            listener.BeginAcceptTcpClient(AcceptTcp, null);

            //开启主循环
            Thread thread = new Thread(MainLoop);
            thread.Start();
        }
        void MainLoop()
        {
            while (true)
            {
                Thread.Sleep(200);
            }
        }

        void AcceptTcp(IAsyncResult ar)
        {
            try
            {
                TcpClient client = listener.EndAcceptTcpClient(ar);//异步接收远程连接
                SocketClient socket = new SocketClient(client);
                string key = client.Client.RemoteEndPoint.ToString();
                //clients.Add(key, socket);

                //再次异步接收客户端连接
                listener.BeginAcceptTcpClient(AcceptTcp, null);
            }
            catch (Exception e)
            {
                LogManager.Log(e.ToString());
            }
        }


        ////广播消息：string
        //public void Broadcast(Protocal type, string msg)
        //{
        //    foreach (var clt in clients)
        //    {
        //        clt.Value.Send(type, msg);
        //    }
        //}
        ////广播消息：byte[]
        //public void Broadcast(Protocal type, byte[] buffer)
        //{
        //    foreach (var clt in clients)
        //    {
        //        clt.Value.Send(type, buffer);
        //    }
        //}
        //给单一客户端发送
        public void SendClient<T>(SocketClient client, Protocal type, T t) where T : ProtoBuf.IExtensible
        {
            client.Send(type, ProtoHelper.Serialize<T>(t));
        }

        //广播给其他登录玩家
        public void SendOther<T>(SocketClient client, Protocal type, T t) where T:ProtoBuf.IExtensible
        {
            foreach (var item in ActorManager.Instance.actors)
            {
                if (item.Value.client != client)
                {
                    item.Value.client.Send(type,ProtoHelper.Serialize<T>(t));
                }
            }
        }
        public void SendAll<T>(Protocal type, T t) where T : ProtoBuf.IExtensible
        {
            foreach (var item in ActorManager.Instance.actors)
            {
                item.Value.client.Send(type, ProtoHelper.Serialize<T>(t));
            }
        }
        //丢失连接
        public void DisConnect(SocketClient client)
        {
            ActorManager.Instance.Remove(client);
        }

        /// <summary>
        /// 接收客户端消息事件分发
        /// </summary>
        /// <param name="buffer">消息[type + content]</param>
        public static void OnEvent(SocketClient client, ByteBuffer buffer)
        {
            Instance.center.ReceiveMessage(client,buffer);
        }
    }
}
